"""
IoT智能家居控制系统 基础视图
"""
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from apps.users.models import UserProfile


@login_required
def profile_view(request):
    """用户资料页面"""
    try:
        profile = request.user.userprofile
    except UserProfile.DoesNotExist:
        profile = UserProfile.objects.create(user=request.user)
    
    if request.method == 'POST':
        # 处理资料更新
        profile.phone = request.POST.get('phone', '')
        profile.address = request.POST.get('address', '')
        profile.theme = request.POST.get('theme', 'light')
        profile.language = request.POST.get('language', 'zh-cn')
        profile.timezone = request.POST.get('timezone', 'Asia/Shanghai')
        
        # 通知设置
        profile.email_notifications = 'email_notifications' in request.POST
        profile.push_notifications = 'push_notifications' in request.POST
        profile.sms_notifications = 'sms_notifications' in request.POST
        
        profile.save()
        messages.success(request, '资料更新成功！')
        return redirect('profile')
    
    context = {
        'profile': profile,
        'device_count': profile.get_device_count(),
        'scene_count': profile.get_scene_count(),
    }
    return render(request, 'auth/profile.html', context)


def health_check(request):
    """系统健康检查"""
    return JsonResponse({
        'status': 'ok',
        'message': 'IoT智能家居控制系统运行正常'
    })